package cn.feilue.app.service.impl;

import cn.feilue.app.service.PersonnelService;
import cn.feilue.app.service.commone.PublicSendValue;
import cn.feilue.app.service.commone.RecipientParam;
import cn.feilue.app.service.commone.SendOptEnum;
import cn.feilue.app.service.config.EmailConfig;
import cn.feilue.app.service.config.RedisUtilDes;
import cn.feilue.app.service.config.SMSConfig;
import cn.feilue.app.service.core.Core;
import cn.feilue.app.service.send.SendSMS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;

import static cn.feilue.app.service.commone.Constants.SEND_EMAILS;
import static cn.feilue.app.service.commone.Constants.SEND_SMS;

@RestController
public class PersonnelServiceImpl implements PersonnelService {
    @Autowired
    private SMSConfig smsConfig;
    @Autowired
    private EmailConfig emailConfig;
    @Autowired
    private RedisUtilDes redisUtil;
    @Autowired
    private Core core;

    private static Logger log =   LoggerFactory.getLogger(SendSMS.class);

    @Override
    public ResponseEntity addRecipient(RecipientParam param) throws Exception {
        SendOptEnum sendOpEnum = SendOptEnum.SMS.getSendOpEnum(param.getSendOpt());
        if(sendOpEnum == null){
            log.error("类型错误");
            return new ResponseEntity<>("类型出错",HttpStatus.OK);
        }
        param.setSendOptEnum(sendOpEnum);
        List<String> all = PublicSendValue.recipientMap.get(param.getSendOptEnum());

        if(all.contains(param.getPersonnel()))
            return new ResponseEntity<>(HttpStatus.OK);

        if(param.getIsAdd() == 1){
            all.add(param.getPersonnel());
            //检查 发送邮件或电话
            core.specifiedSend(param.getPersonnel(), param.getSendOptEnum());
        }else{
            all = rmPersonnel(all, param.getPersonnel());
        }

        PublicSendValue.recipientMap.put(param.getSendOptEnum(),all);
        log.info(param.getSendOptEnum().getOptName()+"队列："+all);

        addRedis(param);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    private void addRedis(RecipientParam param) {
        String opt = SendOptEnum.EMAIL.equals(param.getSendOptEnum()) ?SEND_EMAILS:SEND_SMS;
        if( param.getIsAdd() == 1){
            redisUtil.put(opt, param.getPersonnel(), param.getName());
        }else {
            redisUtil.delete(opt, param.getPersonnel());
        }
    }

    private List<String> rmPersonnel(List<String> list,String personnel){
        for (String s : list) {
            if(personnel.equals(s)){
                list.remove(s);
            }
        }
        return list;
    }

    @Override
    public List<String> recipientList(SendOptEnum sendOptEnum) {
        return PublicSendValue.recipientMap.get(sendOptEnum);
    }
}
